package com.bluesky.example.concurrent;

import java.util.LinkedList;
import java.util.Queue;

public class Buffer {

	Queue<Object> q = new LinkedList<Object>();
	boolean closing = false;

	public synchronized boolean isEmpty() {

		return q.isEmpty();
	}

	public synchronized Object get() {
		

			if (q.isEmpty()) {
				System.out.println("Q is empty and waiting to get");
				try {
					wait();//give up the lock, wait at the tail of the queue
					//wait for the producer to get the lock and put goods and notify
					
					if(isClosed())
					{
						System.out.println("buffer closed.");
						return null;

					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			System.out.println("wait finished, get it");
			return q.poll();

		

	}

	public synchronized void put(Object obj) {
		
		System.out.println("put start");
			q.add(obj);
			
			System.out.println("notify");
			notify();//give up the lock.
			
		
	}

	public synchronized void setClosing(boolean closing) {
		System.out.println("Buffer is closing.");
		if(this.closing==false && closing==true)
			notifyAll();
		
		this.closing = closing;
		
	}

	public synchronized boolean isClosed() {

		return closing && q.isEmpty();
	}
}
